package com.qbccn.bbs.controller;

import com.qbccn.bbs.domain.BbsUser;
import com.qbccn.bbs.service.CommonService;
import com.qbccn.bbs.service.UserService;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author linke
 * @date 2020/5/31 0:11
 * @description
 */
@Controller
public class CommonController {

  @Autowired
  private HttpServletRequest request;
  @Autowired
  private UserService userService;
  @Autowired
  private CommonService commonService;

  @GetMapping("clear")
  @ResponseBody
  public String clear() {
    commonService.clear();
    return "清除缓存成功！";
  }

  /**
   * 用户的主页
   */
  @GetMapping("/u/{id}")
  public String u(@PathVariable("id") Integer id) {
    BbsUser user = userService.getUserById(id);
    if (user == null) {
      return "error/404";
    }
    user.setPassword(null);
    request.setAttribute("user", user);
    request.setAttribute("userLabel", userService.getUserLabel(user.getUsername()));
    return "user/home";
  }

  @GetMapping("/u/me")
  public String u() {
    Object username = request.getSession().getAttribute("username");
    if (username == null) {
      return "redirect:/login";
    }
    BbsUser user = userService.getUser((String) username);
    user.setPassword(null);
    request.setAttribute("user", user);
    request.setAttribute("userLabel", userService.getUserLabel(user.getUsername()));
    return "user/home";
  }
}
